const {
	parser,
	success,
	exception,
	error,
	typeOf,
	Clock,
	timingLogger,
	StatusEnum,
	isArray,
	isNumber
} = require("lg-utils");
const db = uniCloud.database();
const dbCmd = db.command;
/***
	 @type GET 
	 @description : xxx
     @param {
		xxx , xxx
	 }
***/
async function xxx({} = {}) {
	return await xxx
}

/***
	 @type GET 
	 @description : 更新集合指定字段数据;
     @param {
	collection = {}, 集合
	where = {},		 条件
	updater = {}     更新对象
}
***/
async function updateFieldsForColl({
	collection = {},
	where = {},
	updater = {}
} = {}) {
	try {
		const {updated} = await collection.where(where).update(updater) || {};
		if (isNumber(updated)) {
			return success(updated);
		} else {
			return error("更新数据库操作异常;", {
				updated
			});
		}

	} catch (e) {
		return error("更新集合指定字段数据异常;", e);
	}

}



/***
	 @type GET 
	 @description : 添加数组项目
     @param {
		collection = {}, 更新line的集合
		where = {},		 过滤条件
		line = "",		 更项的数组字段名
		list = []        添加的数据列表
	 }
***/
async function pushLineitem({
	collection = {},
	where = {},
	line = "",
	list = []
} = {}) {
	return await collection.where(where).update({
		[line]: dbCmd.push(list)
	})
}

/***
	 @type GET 
	 @description : 尾部弹出数组项目
     @param {
		collection = {}, 更新的集合
		where = {},		 过滤条件
		line = "",		 更项的数组字段名
	 }
***/
async function popLineitem({
	collection = {},
	where = {},
	line = "",
} = {}) {
	return await collection.where(where).update({
		[line]: dbCmd.pop()
	})
}

/***
	 @type GET 
	 @description : 遍历集合
     @param {
		{
		field = {},      指定每次遍历返回的字段
		collection = {}, 遍历的集合
		pageSize = 500,  每页的数量
		lastId = "",     最后 _id
		cycle = 0  		 指定遍历周期
		} ,
		callback = async () => {}  执行回调方法
	}
***/
async function forEachCollection({
	field = {},
	collection = {},
	pageSize = 100,
	lastId = "",
	cycle = 0
} = {}, callback = async () => {}) {
	const succList = [];
	const erroList = [];
	let forEachIndex = 0;
	try {
		do {
			let collRes = {};

			if (lastId === "") {
				collRes = await collection.field(field).limit(pageSize).get();
			} else {
				collRes = await await collection.where({
					_id: dbCmd.gt(lastId)
				}).field(field).limit(pageSize).get();
			}

			const {
				affectedDocs: collResAffect,
				data: collPartList
			} = collRes || {};
			if (typeOf(collResAffect, StatusEnum.NUMBER)) {

				const promises = [];
				for (let [index, iter] of Object.entries(collPartList)) {
					promises.push(callback(iter, forEachIndex, index));
				}
				await Promise.all(promises).then(res => {
					if (typeOf(res, StatusEnum.ARRAY)) {
						const resFilter = res.filter(fi => fi !== undefined);
						succList.push(...resFilter);
					} else {
						succList.push(res);
					}
				}).catch(err => {
					if (typeOf(err, StatusEnum.ARRAY)) {
						erroList.push(...res);
					} else {
						erroList.push(res);
					}
				}).finally(
					() => {
						forEachIndex++;
						console.log(forEachIndex, forEachIndex * pageSize);
					}
				);

				({
					[collPartList.length - 1]: {
						_id: lastId
					} = []
				} = collPartList || []);
			} else {
				return error("分页获取集合数据请求异常.", collResAffect)
			}


		}
		while (lastId && (cycle ? forEachIndex < cycle : true));
		return success({
			succList,
			erroList
		})
	} catch (e) {
		return error("遍历集合异常.", {
			succList,
			erroList,
			e
		})
	}
}

/***
	 @type GET 
	 @description : 获取指定字段所有数据线
     @param {
		field = {} ,    字段对象
		collection = {} 指定集合
		pageSize = 500  分页大小s
	 }
***/
async function getCollForAllByField({
	field = {},
	collection = {},
	pageSize = 500
} = {}) {
	try {


		const {
			data: {
				succList,
				erroList
			}
		} = await forEachCollection({
			collection,
			field,
			pageSize
		}, async (iter) => {
			if (iter) {
				return iter
			} else {
				throw iter
			}
		}) || {};
		if (isArray(succList) && succList.length) {
			if (erroList.length) {
				return error("遍历集合项发生错误;", {
					erroList
				});
			}
			const succListRemaked = succList.map(mi => {
				const temp = {};
				for (let key of Object.keys(field)) {
					temp[key] = mi[key] || "";
				}
				return temp;
			})
			return success(succListRemaked);
		} else {
			return error("遍历集合异常;", succList);
		}
	} catch (e) {
		return error("获取指定字段所有项列表异常;", e);
	}
}


module.exports = {
	forEachCollection,
	pushLineitem,
	popLineitem,
	getCollForAllByField,
	updateFieldsForColl
}
